// src/controllers/messageController.js
const Message = require('../models/Message');
const { logger } = require('../utils/logger');

/**
 * 发送消息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @param {Function} next - 下一步中间件
 */
exports.sendMessage = async (req, res, next) => {
  try {
    const { to, scene, type, content, file_url } = req.body;
    const userId = req.user.id; // 从JWT获取
    const message = new Message({
      from: userId,
      to,
      scene,
      type,
      content,
      file_url,
      timestamp: new Date()
    });
    await message.save();
    logger.info(`Message sent from ${userId} to ${to}`);
    res.status(200).json({ messageId: message._id, timestamp: message.timestamp });
  } catch (err) {
    logger.error('Send message error:', err);
    next(err);
  }
};

/**
 * 获取消息历史
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @param {Function} next - 下一步中间件
 */
exports.getMessageHistory = async (req, res, next) => {
  try {
    const { conversationId, limit = 20, beforeTime } = req.query;
    const userId = req.user.id;
    const query = {
      $or: [
        { from: userId, to: conversationId },
        { from: conversationId, to: userId }
      ]
    };
    if (beforeTime) query.timestamp = { $lt: new Date(beforeTime) };
    const messages = await Message.find(query)
      .sort({ timestamp: -1 })
      .limit(parseInt(limit));
    logger.info(`Fetched message history for ${userId}`);
    res.status(200).json({ messages });
  } catch (err) {
    logger.error('Get message history error:', err);
    next(err);
  }
};